package cn.iocoder.yudao.module.blog.service.improvemanager;

import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.yudao.module.blog.dal.dataobject.improve.BlogImproveDO;
import cn.iocoder.yudao.module.blog.service.improve.BlogImproveService;
import cn.iocoder.yudao.module.member.api.user.MemberUserApi;
import cn.iocoder.yudao.module.member.api.user.dto.MemberUserRespDTO;
import cn.iocoder.yudao.module.trade.dal.dataobject.order.TradeOrderDO;
import cn.iocoder.yudao.module.trade.dal.dataobject.order.TradeOrderItemDO;
import cn.iocoder.yudao.module.trade.enums.order.TradeOrderStatusEnum;
import cn.iocoder.yudao.module.trade.service.order.TradeOrderQueryService;
import cn.iocoder.yudao.module.trade.service.order.TradeOrderUpdateService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;

import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import java.util.*;
import cn.iocoder.yudao.module.blog.controller.admin.improvemanager.vo.*;
import cn.iocoder.yudao.module.blog.dal.dataobject.improvemanager.BlogImproveManagerDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;

import cn.iocoder.yudao.module.blog.convert.improvemanager.BlogImproveManagerConvert;
import cn.iocoder.yudao.module.blog.dal.mysql.improvemanager.BlogImproveManagerMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.blog.enums.ErrorCodeConstants.*;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;

/**
 * 课程权限 Service 实现类
 *
 * @author 曹建伟
 */
@Service
@Validated
public class BlogImproveManagerServiceImpl implements BlogImproveManagerService {

    @Resource
    private BlogImproveManagerMapper improveManagerMapper;

    @Resource
    private TradeOrderUpdateService tradeOrderUpdateService;

    @Resource
    private TradeOrderQueryService tradeOrderQueryService;

    @Resource
    private BlogImproveService blogImproveService;

    @Resource
    private MemberUserApi memberUserApi;

    @Override
    public Long createImproveManager(BlogImproveManagerCreateReqVO createReqVO) {
        BlogImproveManagerDO managerDO = improveManagerMapper.selectOne(new LambdaQueryWrapperX<BlogImproveManagerDO>()
                .eq(BlogImproveManagerDO::getImproveId, createReqVO.getImproveId())
                .eq(BlogImproveManagerDO::getMobile, createReqVO.getMobile()));

        if(managerDO != null){
            throw exception(IMPROVE_MANAGER_HAD_EXISTS);
        }


        // 插入
        BlogImproveManagerDO improveManager = BlogImproveManagerConvert.INSTANCE.convert(createReqVO);
        improveManager.setMemberId(0L);
        improveManagerMapper.insert(improveManager);
        // 返回
        return improveManager.getId();
    }

    @Override
    public void updateImproveManager(BlogImproveManagerUpdateReqVO updateReqVO) {
        // 校验存在
        validateImproveManagerExists(updateReqVO.getId());
        // 更新
        BlogImproveManagerDO updateObj = BlogImproveManagerConvert.INSTANCE.convert(updateReqVO);
        improveManagerMapper.updateById(updateObj);
    }

    @Override
    public void deleteImproveManager(Long id) {
        // 校验存在
        validateImproveManagerExists(id);
        // 删除
        improveManagerMapper.deleteById(id);
    }

    private void validateImproveManagerExists(Long id) {
        if (improveManagerMapper.selectById(id) == null) {
            throw exception(IMPROVE_MANAGER_NOT_EXISTS);
        }
    }

    @Override
    public BlogImproveManagerDO getImproveManager(Long id) {
        return improveManagerMapper.selectById(id);
    }

    @Override
    public List<BlogImproveManagerDO> getImproveManagerList(Collection<Long> ids) {
        if (CollUtil.isEmpty(ids)) {
            return ListUtil.empty();
        }
        return improveManagerMapper.selectBatchIds(ids);
    }

    @Override
    public PageResult<BlogImproveManagerDO> getImproveManagerPage(BlogImproveManagerPageReqVO pageReqVO) {
        return improveManagerMapper.selectPage(pageReqVO);
    }

    @Override
    public List<BlogImproveManagerDO> getImproveManagerList(BlogImproveManagerExportReqVO exportReqVO) {
        return improveManagerMapper.selectList(exportReqVO);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<BlogImproveManagerDO> getMemberImproveList(Long memberId){
        MemberUserRespDTO member = memberUserApi.getUser(memberId);

        this.systemReceiveImproveTradeOrder(member);

        return improveManagerMapper.selectList(BlogImproveManagerDO::getMobile, member.getMobile());
    }

    @Override
    public void systemReceiveImproveTradeOrder(MemberUserRespDTO member){
        List<TradeOrderDO> orderList = tradeOrderQueryService.getOrderByUserIdAndStatus(member.getId(), TradeOrderStatusEnum.UNDELIVERED, true);
        if(orderList.isEmpty()){
            return;
        }

        for(int i = 0; i<orderList.size(); i++){
            TradeOrderDO order = orderList.get(i);
            List<TradeOrderItemDO> orderItemList = tradeOrderQueryService.getOrderItemListByOrderId(order.getId());

            boolean needPickup = false;
            for(int j = 0; j<orderItemList.size();j++){
                tradeOrderUpdateService.pickUpOrderByAdmin(orderItemList.get(j).getOrderId());
                BlogImproveDO improveDO = blogImproveService.getImproveBySkuId(orderItemList.get(j).getSkuId());
                if(improveDO != null){
                    BlogImproveManagerDO managerDO = improveManagerMapper.selectOne(new LambdaQueryWrapperX<BlogImproveManagerDO>()
                            .eq(BlogImproveManagerDO::getMemberId, member.getId())
                            .eq(BlogImproveManagerDO::getImproveId, improveDO.getId()));

                    if(managerDO == null){
                        managerDO = new BlogImproveManagerDO();
                        managerDO.setImproveId(improveDO.getId());
                        managerDO.setMemberId(member.getId());
                        managerDO.setMobile(member.getMobile());
                        improveManagerMapper.insert(managerDO);

                        needPickup = true;
                    }
                }
            }

            if(needPickup){
                tradeOrderUpdateService.pickUpOrderByAdmin(order.getId());
            }
        }

    }

}
